package graphic;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.geom.Matrix;

/**
 * ...
 * @author Damien Mabin
 */

class RenderObjectAnimation 
{
	public var m_FrameNumber		: Int;
	public var m_Frames				: Array<BitmapData>;
	public var m_Duration			: Int;
	
	private var m_CurrentTime		: Int;
	public  var m_CurrentFrame		: BitmapData;
	
	public function new(?_MovieClip:MovieClip) 
	{
		m_Frames = new Array<BitmapData>();
		
		if (_MovieClip != null)
		{
			m_FrameNumber = _MovieClip.totalFrames;
			m_Duration = 2000;
			
			// For each frame
			for(i in 0 ... m_FrameNumber)
			{
				_MovieClip.gotoAndStop(i + 1); // frames goes 1 -> 9
				var frame : BitmapData = new BitmapData(Std.int(_MovieClip.parent.width), Std.int(_MovieClip.parent.height), true, 0x00000000);
				var m : Matrix = new Matrix();
				m.translate(Std.int(_MovieClip.parent.width)/2, Std.int(_MovieClip.parent.height)/2);
				frame.draw(_MovieClip, m);
				m_Frames.push(frame);
			}
		}
	}
	
	public function Clone():RenderObjectAnimation
	{
		var res : RenderObjectAnimation = new RenderObjectAnimation();
		res.m_Duration = m_Duration;
		res.m_FrameNumber = m_FrameNumber;
		res.m_Frames = m_Frames.copy();
		res.m_CurrentTime = this.m_CurrentTime;
		res.m_CurrentFrame = this.m_CurrentFrame;
		return res;
	}
	
	public inline function Start():Void
	{
		m_CurrentTime = 0;
	}
	
	/**
	 * @param	_Delta the time between the last call to Update in millisecond
	 * @return true if the animation is finished
	 */
	public inline function Update(_Delta:Int):Bool
	{
		var res:Bool = false;
		m_CurrentTime += _Delta;
		if (m_CurrentTime > m_Duration)
		{
			res = true;
			m_CurrentTime %= m_Duration;
		}
		
		var nextFrame:BitmapData = m_Frames[Math.floor(m_Frames.length * (m_CurrentTime / m_Duration))];
		m_CurrentFrame = nextFrame;
		return res;
	}
	
	
}